//microcommand define xiujy
const path = require("path")
const execa = require("execa")

const MODES = ["utf8", "utf16be", "utf16", "utf16le", "gb18030", "big5", "shiftjis", "euckr"]
const MODE_SHORTCUTS = { "-8": "utf8", "-6": "utf16", "-g": "gb18030", "-5": "big5" }

signature("<text:rawtext>", { checkUnknown: true })
option("decode", "-d")
option("mode", "<mode>", { params: [MODES.reduce((f, i) => makeArray(f).concat(h.i18n("general.comma"), i)), MODES[0]] })
option("separator", "-P, --no-separator", { value: false })
for (const [flag, value] of Object.entries(MODE_SHORTCUTS))
  option("mode", flag, { value, descPath: `commands.${name}.options.mode.shortcut`, params: [value] })

before(({ session, options, args }) => {
  if (options.help) return
  if ("mode" in options && !MODES.includes(options.mode)) return session.i18n(".invalid-mode")
  if (!args.length) return session.i18n("internal.insufficient-arguments")
})
action(({ session, options }, text) => {
  const argv = [path.resolve(ctx.baseDir, "assets/bin/Xiujy.py")]
  if (options.decode) argv.push("-d")
  else if (options.separator === false) argv.push("-P")
  if (options.mode) argv.push("-c" + options.mode)
  return execa("python3", argv, {
    input: text,
    env: {
      PYTHONIOENCODING: "utf-8",
      PYTHONPATH: path.resolve(ctx.baseDir, "assets/lib"),
    },
  }).then(
    ({ stdout }) => h.text(stdout),
    err => {
      if (typeof err?.stderr === "string")
        return session.i18n(".error", [err.stderr.match(/(?<=\n)\S+Error: [^]+/s)[0] ?? ""])
      throw err
    },
  )
})
locale("zh-CN", {
  description: "编/解码希U语",
  options: {
    decode: "解码",
    mode: "编码方式（可选值：{0}）",
    "mode.shortcut": "等同于 --mode={0}",
    "separator.false": "编码时不输出空格分隔",
  },
  messages: {
    "invalid-mode": "指定的编码方式无效…",
    error: "编码出错…{0}",
  },
})